package com.iotproject.msmservice.controller;

import com.iotproject.commonutils.R;
import com.iotproject.msmservice.service.MsmService;
import com.iotproject.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
//d @CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    MsmService msmService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    //发送验证码并存在Redis
    @GetMapping("getmsg/{phone}")
    public R getMsg(@PathVariable("phone") String phone) {
        //使用redis根据手机号码判断验证码是否过期
        if (!StringUtils.isEmpty(redisTemplate.opsForValue().get(phone))) {//缓存没过期
            return R.ok();
        }
        //缓存过期，直接发送短信
        //生成随机验证码
        String code = RandomUtil.getFourBitRandom();
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        boolean res =  msmService.getMsg(params, phone);//得到验证码
        if (res) {
            //将验证码存在redis，5分钟过期
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("短信发送失败");
    }

}
